package com.btm.easymetadata.server.util;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.util.StringUtils;

import java.util.Map;

public final class WrapperUtil {

    public static String getSql(QueryWrapper<?> wrapper) {
        String result = wrapper.getSqlSegment();
        for (Map.Entry<String, Object> entry : wrapper.getParamNameValuePairs().entrySet()) {
            if (entry.getValue() instanceof Number) {
                result = result.replaceAll("#\\{ew\\.paramNameValuePairs\\." + entry.getKey() + "\\}", String.valueOf(entry.getValue()));
            } else {
                result = result.replaceAll("#\\{ew\\.paramNameValuePairs\\." + entry.getKey() + "\\}", "'" + entry.getValue() + "'");
            }
        }
        return result;
    }

    public static String getSqlStartByAnd(QueryWrapper<?> wrapper) {
        String sql = WrapperUtil.getSql(wrapper);
        if (StringUtils.hasText(sql)) {
            return "and" + sql;
        }
        return sql;
    }
}
